package com.guapi.util;

import com.guapi.util.request.SelfRequest;
import com.guapi.util.request.SelfRequestListener;
import com.guapi.util.request.impl.DefaultRequestListener;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 瓜皮哦
 */
public final class RequestHelper {
    private static ThreadLocal<SelfRequest> localRequestContext = new ThreadLocal<>();
    private static SelfRequestListener requestListener = new DefaultRequestListener();

    public SelfRequestListener getRequestListener() {
        return requestListener;
    }

    public void setRequestListener(SelfRequestListener requestListener) {
        RequestHelper.requestListener = requestListener;
    }

    public static SelfRequest newEmptyRequest() {
        return requestListener.newInstance();
    }

    /**
     * 设置SelfRequest
     * @param selfRequest 新实例
     */
    public static void setCurrentRequest(SelfRequest selfRequest) {
        localRequestContext.set(selfRequest);
    }

    /**
     * 清除当前实例
     */
    public static void clearCurrentRequest() {
        localRequestContext.remove();
    }

    public static SelfRequest getCurrentRequest() {
        return getCurrentRequest(false);
    }

    /**
     * 获取当前线程Request
     * @param returnEmptyForNull 没有值的时候是否返回空实例
     * @return 当前实例或一个空实例
     */
    public static SelfRequest getCurrentRequest(boolean returnEmptyForNull) {
        SelfRequest selfRequest = localRequestContext.get();
        if (selfRequest == null && returnEmptyForNull) {
            return newEmptyRequest();
        }
        return selfRequest;
    }

    public static SelfRequest createServiceRequest(HttpServletRequest httpServletRequest) {
        SelfRequest selfRequest = requestListener.newInstance();
        HttpSession session = httpServletRequest.getSession();
        if (session != null) {
            if (session.getAttribute(SelfRequest.FIELD_USER_ID) != null) {
                selfRequest.setUserId((Long) session.getAttribute(SelfRequest.FIELD_USER_ID));
            }
            if (session.getAttribute(SelfRequest.FIELD_ROLE_ID) != null) {
                selfRequest.setUserId((Long) session.getAttribute(SelfRequest.FIELD_ROLE_ID));
            }
            Object roleIds = session.getAttribute(SelfRequest.FIELD_ALL_ROLE_ID);
            if (roleIds instanceof Long[]) {
                selfRequest.setAllRoleId((Long[]) roleIds);
            }

        } else {

        }
        requestListener.afterInitialize(httpServletRequest, selfRequest);
        return selfRequest;
    }
}
